<?php
namespace App\Http\Controllers\Invite;

use App\Http\Controllers\Controller;
use App\Libraries\Decorator\Image\CoverDecorator;
use App\Libraries\Tools\ConstVar;
use App\Libraries\Tools\Msg;
use App\Models\Banner\Banner;
use App\Models\Invite\Invite;
use App\Models\Invite\InviteCode;
use App\Models\User\Balance;
use App\Models\User\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;


class InviteController extends Controller{



    public function __construct(){}

    public function invite($code, InviteCode $inviteCode, Invite $invite){
        $validator = Validator::make(['code'=>$code], [
            'code' => 'required|string|size:8',
        ], [
            'code.required' => '10001',
            'code.string' => '10002',
            'code.size' => '10002',
        ]);
        if ($validator->fails()) {
            return $this->sendFailResponse(400, $validator->errors()->first());
        }

        $code = $inviteCode->where('code', $code)->first();
        if(empty($code) || empty($code->user_id)){
            return $this->sendFailResponse(400, 40001);
        }

        DB::beginTransaction();
        try{
            $invite->create(['inviter_id'=>$code->user_id, 'invitee_id'=>Auth::id()]);
            User::where('user_id', Auth::id())->increment('balance', 10);
            (new Balance())->add(
                Msg::reward_I_want_cash().'_'.Msg::reward_invitee(),
                0,
                Auth::id(),
                ConstVar::$BALANCE_CHANNEL_BALANCE,
                ConstVar::$BALANCE_CHANNEL_BALANCE,
                ConstVar::$BALANCE_ORIGIN_REWARD,
                $code->user_id,
                10,
                0,0,0,1,
                ConstVar::$BALANCE_TYPE_SYSTEM,
                ConstVar::$BALANCE_TYPE_USER
            );
            DB::commit();
            return $this->sendSuccessResponse([]);
        }catch (\Exception $e){
            DB::rollBack();
            return $this->sendFailResponse(400, 50004);
        }
    }

    public function inviteCode(InviteCode $inviteCode){
        $code = $inviteCode->where('user_id', Auth::id())->first();
        if(empty($code)){
            $code = $inviteCode->whereNull('user_id')->first();
            $code->user_id = Auth::id();
            $code->save();
        }
        return $this->sendSuccessResponse($code);
    }
}